package com.Txunda.fxw.ui.adapter.base;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * 创建时间：2017/12/20 16:08
 * 作    者：Hzj
 * 描    述：所有ListView和GridView的适配器的父类
 * 修    改：2018/10/11日修改。。。
 **/
public abstract class BaseAdapterForLvOrGv<T, VH extends BaseViewHolder> extends BaseAdapter {
    private List<T> list = new ArrayList<>();
    protected Context context;
    private LayoutInflater inflater;

    public BaseAdapterForLvOrGv(Context context) {
        this.context = context;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public T getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    /**
     * 添加数据
     *
     * @param data 数据
     */
    public void updata(List<T> data) {
        list.addAll(data);
        notifyDataSetChanged();
    }

    /**
     * 清除掉所有数据
     */
    public void clear() {
        list.clear();
        notifyDataSetChanged();
    }

    /**
     * 移出某一条数据
     *
     * @param i 下标
     */
    public void removeItem(int i) {
        if (i < 0 || i >= list.size())
            return;
        list.remove(i);
        notifyDataSetChanged();
    }

    /**
     * 获取全部数据
     *
     * @return List
     */
    public List<T> getList() {
        return list;
    }

    // TODO ========== 2018/10/11日修改
    // TODO ========== 2018/10/11日修改
    // TODO ========== 2018/10/11日修改
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        VH baseViewHolder;
        if (view == null) {
            int layoutId = getLayoutId();
            if (layoutId == 0)
                throw new IllegalArgumentException("布局id不能为0");
            view = inflater.inflate(getLayoutId(), viewGroup, false);
            baseViewHolder = createViewHolder(view);
            view.setTag(baseViewHolder);
        } else
            baseViewHolder = (VH) view.getTag();
        bindViewData(i, baseViewHolder, getItem(i));
        return view;
    }

    /**
     * 设置item布局id
     *
     * @return int
     */
    protected abstract int getLayoutId();

    /**
     * 创建一个继承自BaseViewHolder的VH
     *
     * @param view view
     * @return VH
     */
    protected abstract VH createViewHolder(View view);

    /**
     * 绑定数据
     *
     * @param position 下标
     * @param vh       ViewHolder
     * @param item     数据
     */
    protected abstract void bindViewData(int position, VH vh, T item);
}
